package chd.edu.spzx.manager.task;

import chd.edu.spzx.manager.mapper.OrderInfoMapper;
import chd.edu.spzx.manager.mapper.OrderStatisticsMapper;
import chd.edu.spzx.model.entity.order.OrderStatistics;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Zhang Chaoliang
 * create 2023
 */
@Component
public class OrderStatisticsTask {

    //测试定时任务方法
    //每隔5s执行一次
    //注解：@Scheduled  + cron表达式
    //cron表达式设置执行规则
//    @Scheduled(cron = "0/5 * * * * ? ")
//    public void testHello(){
//        System.out.println(new Date().toInstant());
//    }

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    /**
     * 每天凌晨2点，查询前一天统计数据，把统计之后的数据添加到统计结果表中
     */
//    @Scheduled(cron = "0/10 * * * * ? ")  //TODO 测试
    @Scheduled(cron = "0 0 2 * * ? ")
    public void orderTotalAmountStatistics(){
        System.out.println(new Date().toInstant());
        //1. 获取前一天日期
        String createTime = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");

        //2. 根据前一天日期进行统计功能（分组操作）
        //统计前一天交易金额
        OrderStatistics orderStatistics = orderInfoMapper.selectStatisticsByDate(createTime);

        //3. 把统计之后的数据，添加到统计结果表中
        if (orderStatistics!=null){
            orderStatisticsMapper.insert(orderStatistics);
        }

    }

}
